/*lF5ufsCmKWn338wa/NhzEjDORqNoqQ1/VcaVU8wTLwtxognE09JxW0fayJTPBgHW*/
import React, { Component } from 'react';
import { ajax, base, toast,formatNumber,sum} from 'nc-lightapp-front';
import { forEach } from 'lodash';
const { NCNumber,NCButton } = base;
export{
    selectArea,onCheckedChange,onClearAll,getCheckedRowPK,updateCheckedRowsCurrentDealMny,updatePullMoney
}
function onClearAll(){
    let {pullMoney}=this.state;
    pullMoney.value='';
    this.setState({
        pullMoney
    })
}
function selectArea(param){
    let self=this;
    let {pullMoney,json}=self.state;
    let {headId, bodyId, selectedShow, body_pkname}=param;

    if(!pullMoney.value){
        let allCheckedRows=self.props.transferTable.getTransferTableSelectedValue();
        let src_appcode=self.props.getUrlParam('src_appcode')||self.props.getSearchParam('src_appcode');
        let checkedData=allCheckedRows[headId];
        let checkedSum=0;
        for (let i=0;i<checkedData.length;i++){
            let checkedRows=checkedData[i].body[src_appcode+'_bodys']&&checkedData[i].body[src_appcode+'_bodys'].rows||[];
            for (let j=0;j<checkedRows.length;j++){
                checkedSum=sum(Number(checkedSum),Number(checkedRows[j].values.currentDealMny && checkedRows[j].values.currentDealMny.value));
                if(checkedSum.indexOf(',')!=-1){
                    checkedSum=checkedSum.replace(/,/g,'');
                }
            }
        }
        pullMoney.value = checkedSum;
    }
    return !selectedShow?(
        <div className="arapPullMoney extention-area">
            <div className='extention-item'>
                <span className='extention-item-title'>{json['public-000283']}</span> {/* 国际化处理： 本次处理金额：*/}
                <NCNumber
                    fieldid="financeNum"
                    style={{ 'text-align': 'left' }}
                    // className="arapPullMoney"
                    value={pullMoney.value}
                    scale={pullMoney.scale}
                    onChange={(v) => {
                        pullMoney.value = Number(v).toString();
                        self.setState({
                            pullMoney
                        });
                    }}
                />
                <NCButton colors="primary" fieldid='comfirm' onClick={allocation.bind(this,param)}>{json['public-000284']}</NCButton>{/* 分配 */}
            </div>
        </div>
    ):(<div></div>)
}
/**
 * currentDealMny 本次处理 Math.abs
 * 规则：1、输入0 不能分配；
 * 2、输入负数跳过正数，按绝对值来分配，比如-3，-100，只能分配-3；
 * 3、输入正数跳过负数，按绝对值来分配，比如3，100，只能分配3；
*/
function allocation(param){
    let self=this;
    let  {pullMoney,json}=self.state;
    let {headId, bodyId}=param;
    if((pullMoney&&Number(pullMoney.value)==0)){
        toast({content:json['public-000282'],color:'warning'});//请先输入需要分配的金额
        return;
    }
    let checkedFlag=false;
    self.props.transferTable.clearAllSelectedData();//先清空所有已选数据
    let allocationMoney=Number(pullMoney.value);
    let allTableRow=self.props.transferTable.getTransferTableValue(headId);
    let bodyData=allTableRow&&allTableRow[headId]&&allTableRow[headId].bodyData&&allTableRow[headId].bodyData.data;
    if(bodyData&&Object.getOwnPropertyNames(bodyData).length!=0){
        let pks=[],sumMoney=0,isBreak=false,surplusMoney=allocationMoney;
        for(let pk in bodyData){
            let rows=bodyData[pk].rows;
            rows.forEach((row,index)=>{
                let childId=row.childId;
                if(row.values.currentDealMny){
                    row.values.currentDealMny.value='';
                }
                //判断金额
                let occupationmny=row.values.occupationmny.value;
                try{
                    // if(sumMoney==allocationMoney){
                    if(surplusMoney==0){
                        isBreak=true;
                        throw new Error(allocationMoney);
                    }
                    let isPositiveNum=Number(allocationMoney)>0?true:false;
                    if(Number(allocationMoney)>0){//正数
                        if(Number(occupationmny)>=0){
                            if(Number(surplusMoney)-Number(occupationmny)>=0){
                                surplusMoney=sum(Number(surplusMoney),-Number(occupationmny));
                                if(surplusMoney.indexOf(',')!=-1){
                                    surplusMoney=surplusMoney.replace(/,/g,'');
                                }
                                if(row.values.currentDealMny) {
                                    row.values.currentDealMny.value=occupationmny;
                                }else{
                                    row.values.currentDealMny={
                                        ...row.values.occupationmny,
                                        value:occupationmny
                                    };
                                }   
                                pks.push(childId);
                            }else{
                                let restMoney=surplusMoney;
                                surplusMoney=0;
                                if(row.values.currentDealMny) {
                                    row.values.currentDealMny.value=restMoney;
                                }else{
                                    row.values.currentDealMny={
                                        ...row.values.occupationmny,
                                        value:restMoney
                                    };
                                }
                                pks.push(childId);
                                // sumMoney=allocationMoney;
                            }
                        }
                    }else if(Number(allocationMoney)<0){//负数
                        if(Number(occupationmny)<0){
                            if(Math.abs(surplusMoney)-Math.abs(occupationmny)>=0){
                                surplusMoney=sum(Number(surplusMoney),-Number(occupationmny));
                                if(surplusMoney.indexOf(',')!=-1){
                                    surplusMoney=surplusMoney.replace(/,/g,'');
                                }
                                if(row.values.currentDealMny) {
                                    row.values.currentDealMny.value=occupationmny;
                                }else{
                                    row.values.currentDealMny={
                                        ...row.values.occupationmny,
                                        value:occupationmny
                                    };
                                }   
                                pks.push(childId);
                            }else{
                                let restMoney=surplusMoney;
                                surplusMoney=0;
                                if(row.values.currentDealMny) {
                                    row.values.currentDealMny.value=restMoney;
                                }else{
                                    row.values.currentDealMny={
                                        ...row.values.occupationmny,
                                        value:restMoney
                                    };
                                }
                                pks.push(childId);
                                // sumMoney=allocationMoney;
                            }
                        }
                    }
                    // if(Number(surplusMoney)>0||(Number(surplusMoney)<0&&Number(surplusMoney)-Number(occupationmny)>=0)){
                    //     if(Number(surplusMoney)-Number(occupationmny)>=0){
                    //     // if(Number(sumMoney)+Number(occupationmny)<=allocationMoney){
                    //         // sumMoney=sum(Number(sumMoney),Number(occupationmny));
                    //         // surplusMoney=Number(surplusMoney)-Number(occupationmny);
                    //         surplusMoney=sum(Number(surplusMoney),-Number(occupationmny));
                    //         if(surplusMoney.indexOf(',')!=-1){
                    //             surplusMoney=surplusMoney.replace(/,/g,'');
                    //         }
                    //         if(row.values.currentDealMny) {
                    //             row.values.currentDealMny.value=occupationmny;
                    //         }else{
                    //             row.values.currentDealMny={
                    //                 ...row.values.occupationmny,
                    //                 value:occupationmny
                    //             };
                    //         }   
                    //         pks.push(childId)
                    //     }else{
                    //         let restMoney=surplusMoney;//allocationMoney-sumMoney;
                    //         surplusMoney=0;
                    //         if(row.values.currentDealMny) {
                    //             row.values.currentDealMny.value=restMoney;
                    //         }else{
                    //             row.values.currentDealMny={
                    //                 ...row.values.occupationmny,
                    //                 value:restMoney
                    //             };
                    //         }
                    //         pks.push(childId);
                    //         // sumMoney=allocationMoney;
                    //     }
                    //     self.props.transferTable.setRowDataByIndex(headId, row.values, index);
                    // }else{
                    //     isBreak=true;
                    //     toast({content:json['public-000300'],color:'warning'});//分摊失败
                    //     throw new Error(allocationMoney);
                        
                    // }
                }catch(e){
                    if (e.message!=allocationMoney) {
                        toast({content:json['public-000300'],color:'warning'});//分摊失败
                        throw e;   
                    }
                }
            })
            if(isBreak){
                continue;
                // break;
            }
        }
        if(pks&&pks.length>0){
            self.props.transferTable.setTheCheckRows(headId, pks);
            checkedFlag=true;
        }
        
    }else{
        toast({content:json['public-000281'],color:'warning'});//暂无转单数据可分配
        return;
    }
    if(checkedFlag){
        toast({content:json['public-000299'],color:'success'});//分摊成功
    }else{
        toast({content:json['public-000300'],color:'warning'});//分摊失败
    }
}
function onCheckedChange(flag, record, index, bodys,rest){ //勾选的回调函数
    let self=this;
    let {headId, bodyId,body_pkname}=rest;
    let {pullMoney}=self.state;
    let allCheckedRows=self.props.transferTable.getTransferTableSelectedValue();
    let src_appcode=self.props.getUrlParam('src_appcode')||self.props.getSearchParam('src_appcode');
    let checkedData=allCheckedRows[headId];
    let checkedSum=0,checkedRowPK=[];
    for (let i=0;i<checkedData.length;i++){
        let checkedRows=checkedData[i].body[src_appcode+'_bodys']&&checkedData[i].body[src_appcode+'_bodys'].rows||[];
        checkedRows.forEach((row,index)=>{
            let record=row.values;
            let pk=record[body_pkname].value;
            if(!checkedRowPK.includes(pk)){
                checkedRowPK.push(pk);
            }
        })
    }
    let allTableRow=self.props.transferTable.getTransferTableValue(headId);
    let bodyData=allTableRow&&allTableRow[headId]&&allTableRow[headId].bodyData&&allTableRow[headId].bodyData.data;
    for(let pk in bodyData){
        let rows=bodyData[pk].rows;
        rows.forEach((row,index)=>{
            let record=row.values;
            let pk=record[body_pkname].value;
            if(checkedRowPK.includes(pk)){
                let occupationmny=record.occupationmny.value;
                if(record.currentDealMny && record.currentDealMny.value == '') {
                    record.currentDealMny.value = occupationmny;
                } else if (!record.currentDealMny) {
                    record.currentDealMny={
                        ...row.values.occupationmny,
                        value:occupationmny
                    };
                } 
                self.props.transferTable.setRowDataByIndex(headId, record, index);
                checkedSum=sum(Number(checkedSum),Number(record.currentDealMny&&record.currentDealMny.value));
                if(checkedSum.indexOf(',')!=-1){
                    checkedSum=checkedSum.replace(/,/g,'');
                }
            }else{
                if(record.currentDealMny) {
                    record.currentDealMny.value='';
                }
                self.props.transferTable.setRowDataByIndex(headId, record, index);
            }
        })
    }
    // updateTransferTableValue(id, childCode, newData, rowId, childId) 
    pullMoney.value=checkedSum?checkedSum:'';
    this.setState({
        pullMoney
    })
}
function getCheckedRowPK(param){
    let self=this;
    let {headId, bodyId,body_pkname}=param;
    let {pullMoney}=self.state;
    let allCheckedRows=self.props.transferTable.getTransferTableSelectedValue();
    let src_appcode=self.props.getUrlParam('src_appcode')||self.props.getSearchParam('src_appcode');
    let checkedData=allCheckedRows[headId];
    let checkedSum=0,checkedRowPK=[];
    for (let i=0;i<checkedData.length;i++){
        let checkedRows=checkedData[i].body[src_appcode+'_bodys']&&checkedData[i].body[src_appcode+'_bodys'].rows||[];
        checkedRows.forEach((row,index)=>{
            let record=row.values;
            let pk=record[body_pkname].value;
            if(!checkedRowPK.includes(pk)){
                checkedRowPK.push(pk);
            }
        })
    }
    return checkedRowPK;
}
function updateCheckedRowsCurrentDealMny(param){
    let self=this;
    let {checkedRowPK,data,headId, bodyId,body_pkname}=param;
    let checkedSum=0;
    if(checkedRowPK&&checkedRowPK.length>0){
        data.forEach((row,index)=>{
            let bodyRows=row.body[bodyId].rows;
            bodyRows.forEach((row,index)=>{
                let record=row.values;
                let pk=record[body_pkname].value;
                if(checkedRowPK.includes(pk)){
                    let occupationmny=record.occupationmny.value;
                    if(record.currentDealMny && record.currentDealMny.value == '') {
                        record.currentDealMny.value = occupationmny;
                    } else if (!record.currentDealMny) {
                        record.currentDealMny={
                            ...row.values.occupationmny,
                            value:occupationmny
                        };
                    } 
                    checkedSum=sum(Number(checkedSum),Number(record.currentDealMny&&record.currentDealMny.value));
                    if(checkedSum.indexOf(',')!=-1){
                        checkedSum=checkedSum.replace(/,/g,'');
                    }
                }else{
                    if(record.currentDealMny) {
                        record.currentDealMny.value='';
                    }
                }
            })
        })
    }
    return {resultData:data,pullMoney:checkedSum}
}
function updatePullMoney(checkedSum){
    let {pullMoney}=this.state;
    pullMoney.value=checkedSum;
    this.setState({
        pullMoney
    })
}
/*lF5ufsCmKWn338wa/NhzEjDORqNoqQ1/VcaVU8wTLwtxognE09JxW0fayJTPBgHW*/